package com.jinlejia.erp.ui.house;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.ListMapDropDownAdapter;
import com.jinlejia.erp.adapter.SellingAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.SearchShsCoreBean;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.databinding.FragmentSellingBinding;
import com.jinlejia.erp.utils.DataFilter;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 出售的房源
 */
public class SellingFragment extends Fragment implements YfLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    protected Activity mActivity;
    private View view;

    private String headers[] = {"全部房源", "价格区间", "居室", "更多"};
    private List<View> popupViews = new ArrayList<>();
    private ListMapDropDownAdapter houseMenuAdapter;
    private ListMapDropDownAdapter roomMenuAdapter;
    private ListMapDropDownAdapter priceMenuAdapter;

    private static SellingAdapter adapter;

    private JSONObject jsonObject = new JSONObject();
    private JSONObject moreJsonObject = new JSONObject();
    private int page = 1;
    private boolean mLoadingLock = false;
    private ArrayList<Map<String, Object>> dataList = new ArrayList<>();
    private ArrayList<Map<String, Object>> houseTypeList = new ArrayList<>();
    private ArrayList<Map<String, Object>> roleList = new ArrayList<>();
    private ArrayList<Map<String, Object>> salePriceList = new ArrayList<>();

    private ArrayList<String> moreSelectList = new ArrayList<>();
    private ArrayList<String> chageStateSelectList = new ArrayList<>();
    private String jsonString;

    private FragmentSellingBinding binding;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_selling, container, false);
        binding = DataBindingUtil.bind(view);
        EventBus.getDefault().register(this);
        binding.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.refreshLayout.setOnRefreshListener(this);
        initView();
        getHeadDictionary();
        getData();

        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (Activity) context;
    }

    private void initView() {

        //房源菜单 menu
        final ListView houseView = new ListView(mActivity);
        houseMenuAdapter = new ListMapDropDownAdapter(mActivity, roleList);
        houseMenuAdapter.setData(roleList);
        for (int i = 0; i < roleList.size(); i++) {
            if (roleList.get(i).get("valueName").equals("本商圈房源")) {
                jsonObject.put("flag", roleList.get(i).get("valuel").toString());
                houseMenuAdapter.setCheckItem(i + 1);
                headers[0] = "本商圈房源";
            }
        }
        houseView.setDivider(mActivity.getResources().getDrawable(R.drawable.shape_h_line));
        houseView.setAdapter(houseMenuAdapter);
        //房源点击
        houseView.setOnItemClickListener((parent, view, position, id) -> {
            headers[0] = "全部房源";
            houseMenuAdapter.setCheckItem(position);
            binding.dropDownMenu.setTabText(position == 0 ? headers[0] : roleList.get(position).get("valueName").toString());
            binding.dropDownMenu.closeMenu();
//                System.out.println( roleList.get(position).entrySet() );
            if (roleList.get(position).containsKey("valuel")) {
                jsonObject.put("flag", roleList.get(position).get("valuel").toString());
            } else {
                jsonObject.put("flag", "");
            }
            page = 1;
            getData();
        });

        //价格区间
        final View priceAreaFooter = mActivity.getLayoutInflater().inflate(R.layout.selling_price_area_footer, null);
        final ListView priceAreaView = new ListView(mActivity);
        priceMenuAdapter = new ListMapDropDownAdapter(mActivity, salePriceList);
        priceAreaView.setDivider(mActivity.getResources().getDrawable(R.drawable.shape_h_line));
        priceAreaView.addFooterView(priceAreaFooter);
        priceAreaView.setAdapter(priceMenuAdapter);
        //价格输入框
        final EditText leftPrice = priceAreaFooter.findViewById(R.id.et_left);
        final EditText rightPrice = priceAreaFooter.findViewById(R.id.et_right);
        //重置、确定按钮
        TextView cancel = priceAreaFooter.findViewById(R.id.bt_cancel);
        TextView confirm = priceAreaFooter.findViewById(R.id.bt_confirm);
        //价格列表点击
        priceAreaView.setOnItemClickListener((parent, view, position, id) -> {
            priceMenuAdapter.setCheckItem(position);
            binding.dropDownMenu.setTabText(position == 0 ? headers[1] : salePriceList.get(position).get("valueName").toString());
            binding.dropDownMenu.closeMenu();
            if (salePriceList.get(position).containsKey("minValue")) {
                jsonObject.put("salePrice_start", salePriceList.get(position).get("minValue").toString());
                jsonObject.put("salePrice_end", salePriceList.get(position).get("maxValue").toString());
            } else {
                jsonObject.put("salePrice_start", "");
                jsonObject.put("salePrice_end", "");
            }
            page = 1;
            getData();
        });
        //点击重置
        cancel.setOnClickListener(v -> {
            leftPrice.setText("");
            rightPrice.setText("");
        });
        //确定按钮
        confirm.setOnClickListener(v -> {
            if (TextUtils.isEmpty(leftPrice.getText().toString())) {
                Toast.makeText(mActivity, "请输入最低价格", Toast.LENGTH_SHORT).show();
            } else if (TextUtils.isEmpty(rightPrice.getText().toString())) {
                Toast.makeText(mActivity, "请输入最高价格", Toast.LENGTH_SHORT).show();
            } else if (Integer.parseInt(leftPrice.getText().toString()) > Integer.parseInt(rightPrice.getText().toString())) {
                CustomToast.showToast(mActivity, "最大价格必须大于最小价格", 1500);
            } else {
                binding.dropDownMenu.setTabText(leftPrice.getText().toString().concat("万-").concat(rightPrice.getText().toString()).concat("万"));
                binding.dropDownMenu.closeMenu();
                jsonObject.put("salePrice_start", leftPrice.getText().toString());
                jsonObject.put("salePrice_end", rightPrice.getText().toString());
                page = 1;
                getData();
            }
        });


        //  居室
        final ListView roomView = new ListView(mActivity);
        roomMenuAdapter = new ListMapDropDownAdapter(mActivity, houseTypeList);
        roomView.setDivider(mActivity.getResources().getDrawable(R.drawable.shape_h_line));
        roomView.setAdapter(roomMenuAdapter);
        //居室点击
        roomView.setOnItemClickListener((parent, view, position, id) -> {
            roomMenuAdapter.setCheckItem(position);
            binding.dropDownMenu.setTabText(position == 0 ? headers[2] : houseTypeList.get(position).get("valueName").toString());
            binding.dropDownMenu.closeMenu();
            if (houseTypeList.get(position).containsKey("valuel")) {
                jsonObject.put("houseType", houseTypeList.get(position).get("valuel").toString());
            } else {
                jsonObject.put("houseType", "");
            }
            page = 1;
            getData();
        });


        //  更多
        final View moreView = new View(mActivity);

        // 添加到view List
        popupViews.add(houseView);
        popupViews.add(priceAreaView);
        popupViews.add(roomView);
        popupViews.add(moreView);


        TextView contentView = new TextView(mActivity);
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);
//        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);

        //init dropdownview
        binding.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);
        binding.dropDownMenu.setOnMenuChangeListener(menuID -> {
            if (menuID == 6) {
                //更多
                binding.dropDownMenu.closeMenu();
                Intent intent = new Intent(mActivity, MenuMoreActivity.class);
                intent.putExtra("type", "shs");
                intent.putStringArrayListExtra("selectList", moreSelectList);
                intent.putExtra("jsonString", jsonString);
                if (chageStateSelectList.size() > 0) {
                    intent.putStringArrayListExtra("chageStateSelectList", chageStateSelectList);
                }

                startActivityForResult(intent, 100);
            }
        });

        binding.rvHouseList.setLayoutManager(new LinearLayoutManager(mActivity));
        binding.rvHouseList.addItemDecoration(new RecycleViewDivider(
                mActivity, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));
        binding.rvHouseList.setHasFixedSize(true);
        binding.rvHouseList.enableAutoLoadMore(this);

        adapter = new SellingAdapter(dataList);
        binding.rvHouseList.setAdapter(adapter);
        adapter.changeMode(YfListMode.MODE_LOADING);
        binding.rvHouseList.addItemDecoration(new RecycleViewDivider(
                mActivity, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));

        adapter.setOnItemClickListener((view, o) -> {
            Map<String, Object> map = (Map<String, Object>) o;
            Intent intent = new Intent(mActivity, HouseDetailActivity.class);
            intent.putExtra("type", "shs");
            intent.putExtra("code", map.get("rscode").toString());
            intent.putExtra("name", map.get("estate").toString());
            intent.putExtra("isDuty",String.valueOf(map.get("isDuty")));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        });

    }

    private void getData() {
        binding.refreshLayout.setRefreshing(true);
        mLoadingLock = true;
        jsonObject.put("pageSize", 20);
        jsonObject.put("pageIndex", page);
        JSONObject postJson = new JSONObject();
        postJson.putAll(jsonObject);
        if (!moreJsonObject.isEmpty())
            postJson.putAll(moreJsonObject);
        OkHttpUtils.postString()
                .url(ApiConfig.Sell_HOUSE_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(postJson.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        if (binding.refreshLayout.isRefreshing()) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (binding.refreshLayout.isRefreshing()) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                        if (DataFilter.filter(mActivity, response, adapter)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            binding.tvHouseCount.setText(data.get("count").toString());
                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(data.getJSONArray("list").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (null == list)
                                list = new ArrayList<>();
                            if (page == 1) {
                                adapter.setData(list);
                            } else {
                                adapter.addData(list);
                            }
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            if (page > 0)
                                page--;
                        } else if (response.get("code").toString().equals("501")) {

                            binding.tvHouseCount.setText("0");
                        }
                        if (binding.refreshLayout.isRefreshing()) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                        mLoadingLock = false;
                    }
                });
    }

    @Override
    public void loadMore() {
        if (adapter.getData().size() % 20 == 0) {
            if (mLoadingLock) {
                return;
            }
            mLoadingLock = true;
            page++;
            adapter.addFooter("loading");

            getData();
        } else if (adapter.getData().size() > 10) {
            adapter.addFooter(R.string.is_all);
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        getData();
    }

    private void getHeadDictionary() {
        binding.refreshLayout.setRefreshing(true);
        OkHttpUtils.get()
                .url(ApiConfig.HOUSE_HEAD_DICTIONARY.concat("shs"))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                        if (binding.refreshLayout.isRefreshing())
                            binding.refreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (binding.refreshLayout.isRefreshing())
                            binding.refreshLayout.setRefreshing(false);
                        if (DataFilter.filter(mActivity, response)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            houseTypeList = JSON.parseObject(data.getJSONArray("houseTypeList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            roleList = JSON.parseObject(data.getJSONArray("roleList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            salePriceList = JSON.parseObject(data.getJSONArray("salePriceList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            houseMenuAdapter.setData(roleList);
                            roomMenuAdapter.setData(houseTypeList);
                            priceMenuAdapter.setData(salePriceList);
                        }
                    }
                });
    }

    @Subscriber(tag = "TAG_SEARCH_SHS")
    public void data(String name) {
        handler.sendEmptyMessage(0);
        jsonObject.put("key", name);
        page = 1;
        getData();
    }

    @Subscriber(tag = "TAG_SEARCH_SHS_HISTORY")
    public void filterData(SearchShsCoreBean sscb) {
        jsonObject.put("key", sscb.getEaste());
        jsonObject.put("buildingNo", sscb.getBuildingNo());
        jsonObject.put("unitNo", sscb.getUnitNo());
        jsonObject.put("houseNo", sscb.getRoomNo());
        page = 1;
        getData();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == 100) {
            if (data.hasExtra("jsonString") && !TextUtils.isEmpty(data.getStringExtra("jsonString")))
                jsonString = data.getStringExtra("jsonString");
            moreSelectList = data.getStringArrayListExtra("selectList");
            moreJsonObject = JSONObject.parseObject(jsonString);
            chageStateSelectList.clear();
            if (data.hasExtra("chageStateSelectList")) {
                chageStateSelectList = data.getStringArrayListExtra("chageStateSelectList");
            }

//            if( object.size()>0 ) {
//            jsonObject.putAll(object);
//        }else{
//            jsonObject.clear();
//        }
            page = 1;
            handler.sendEmptyMessage(0);
//            jsonObject.clear();
            getData();
        }
    }

    static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != adapter)
                adapter.changeMode(YfListMode.MODE_LOADING);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
